<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\Tk_QuestionImportRequest;
use App\Models\Course;
use App\Models\Knowledge;
use App\Models\Questions;
use App\Service\Office\PaperImportService;
use App\Service\Office\WordService;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\JsonResponse;
use Log;
use PhpOffice\PhpWord\Settings;

class QuestionController extends AdminBaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return JsonResponse|object
     */
    public function index()
    {
        $list = Questions::filter(\request()->all())
            ->with(['course' => function($q) {
                $q->select(['id', 'courseName', 'fullName']);
            }, 'knowledge' => function($q) {
                $q->select(['id', 'knowledgeName']);
            }])
            ->orderByDesc('id')
            ->paginate(\request('perPage', 10));
        return $this->restful($list);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param int $id
     * @return JsonResponse|object
     */
    public function destroy(int $id)
    {
        $result = Questions::where('id', $id)->delete();

        return $this->restful($result);
    }

    /**
     * 导入
     * @param Tk_QuestionImportRequest $request
     * @param WordService $wordService
     * @param PaperImportService $paperImport
     * @return JsonResponse|object
     * @throws Exception
     */
    public function import(Tk_QuestionImportRequest $request, WordService $wordService, PaperImportService $paperImport) {
        // 表单数据
        $params = $request->validated();
        if (empty($params['pathType'])) $params['pathType'] = 1;
        if ($params['pathType'] == 2) {
            $filePath = $params['filePath'];
        } else {
            $filePath = storage_path($params['filePath']);
        }

        $knowledge = Knowledge::where('id', $params['knowledgeId'])->where('level', 3)->firstOrFail();

        if (empty($params['courseId'])) $params['courseId'] = $knowledge->courseId;

        if (empty($params['city'])) $params['city'] = null;

        $wordService->imgPath = 'tikuimg/paper/'.$params['courseId'].'/'.Carbon::now()->format('Y/m').'/';
        $paperImport->imgPath = 'tikuimg/paper/'.$params['courseId'].'/'.Carbon::now()->format('Y/m').'/';

        // 所有题目，目前只记录父级题目
        $questionIds = [];

        try {
            // docx 转 html
            $html = $wordService->docx2html($filePath);

            // 解析试卷
            $questions = $wordService->htmlHandle($html, $params['courseId']);
        }catch (Exception $e) {
            Log::error('[试卷导入-格式有误]', (array)$e);
            throw new Exception('试卷格式有误');
        }

        // 入库
        try {
            // 试题入库
            foreach ($questions as $question) {
                $Q = $paperImport->saveQuestionToDatabase($question, $params['courseId'], $params['province'], $params['city'], true, $knowledge);
                if ($Q) {
                    $questionIds[] = $Q['id'];
                }else {
                    throw new Exception('试题入库失败');
                }
            }
        }catch (Exception $e) {
            Log::error('[试卷导入]', (array)$e);
            Log::error($e->getMessage());
            throw new Exception('导入失败');
        }

        // 成功
        return $this->restful($questionIds);
    }

    public function getQuestionCascadeOptions() {
        $courses = Course::selectRaw('id as value, courseName as label, studyName, studyType')
            ->orderByRaw('studyType asc, id asc')
            ->get()
            ->groupBy('studyName');

        $list = collect($courses)->map(function ($group, $groupName) {
            return [
                'label' => $groupName,
                'value' => $group[0]->studyType,
                'children' => $group->map(function ($course) {
                    return [
                        'label' => $course->label,
                        'value' => $course->value,
                        'children' => request('level') != 1 ? Knowledge::where('courseId', $course->value)->where('level', 3)->selectRaw('id, knowledgeName')->get()->map(function ($knowledge) {
                            return [
                                'label' => $knowledge->knowledgeName,
                                'value' => $knowledge->id
                            ];
                        })->toArray() : []
                    ];
                })->toArray()
            ];
        })->values()->toArray();

        return $this->restful($list);
    }
}
